package com.yao.longhan.ui.activity;

import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatDelegate;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.yao.longhan.R;
import com.yao.longhan.constant.Constant;
import com.yao.longhan.manager.SettingManager;
import com.yao.longhan.manager.ThemeManager;
import com.yao.longhan.model.BookCatalog;
import com.yao.longhan.model.Catalog;
import com.yao.longhan.model.StoryArticle;
import com.yao.longhan.net.BaseCallback;
import com.yao.longhan.presenter.easyadapter.ReadThemeAdapter;
import com.yao.longhan.support.ReadTheme;
import com.yao.longhan.ui.base.BaseActivity;
import com.yao.longhan.ui.widget.BaseReadView;
import com.yao.longhan.utils.ScreenUtils;
import com.yao.longhan.utils.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by heyao on 2017/8/7.
 */

public class ReadActivity1 extends BaseActivity {

    //    @BindView(R.id.rlBookReadRoot)
    RelativeLayout mRlBookReadRoot;

    //    @BindView(R.id.llBookReadTop)
    LinearLayout mLlBookReadTop;
    //    @BindView(R.id.tvBookReadTocTitle)
    TextView tvTitle;

    //    @BindView(R.id.tvFontsizeMinus)
    TextView tvFontsizeMinus;

    //    @BindView(R.id.seekbarFontSize)
    SeekBar seekBarFontSize;

    //    @BindView(R.id.tvFontsizePlus)
    TextView tvFontsizePlus;

    //    @BindView(R.id.ivBrightnessMinus)
    ImageView ivBrightnessMinus;

    //    @BindView(R.id.seekbarLightness)
    SeekBar seekBarLightness;

    //    @BindView(R.id.ivBrightnessPlus)
    ImageView ivBrightnessPlus;

    //    @BindView(R.id.gvTheme)
    GridView gvTheme;

    //    @BindView(R.id.tvBookReadMode)
    TextView mTvBookReadMode;

    private BaseReadView mPageWidget;
    private View decodeView;
    private int chapterPage = 0;
    private ArrayList<Catalog> chapList;
    private int REQUEST_CATALOG = 100;
    private String bookId;
    private int currentChapter;

    private int curTheme = -1;
    private List<ReadTheme> themes;
    private ReadThemeAdapter gvAdapter;
    private boolean isAutoLightness = false; // 记录其他页面是否自动调整亮度

    @Override
    protected int inflateLayout() {
        return R.layout.activity_read;
    }

    @Override
    protected void initBefore() {
        super.initBefore();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        statusBarColor = ContextCompat.getColor(this, R.color.reader_menu_bg_color);
    }

    @Override
    protected void initAfter() {
        initData();
        hideStatusBar();
        decodeView = getWindow().getDecorView();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLlBookReadTop.getLayoutParams();
        params.topMargin = ScreenUtils.getStatusBarHeight(this) - 2;
        mLlBookReadTop.setLayoutParams(params);

        // TODO: 8/11/17 如果已下载直接打开
    }

    private void initData() {
        showDialog();
        Bundle bundle = getIntent().getExtras();
        StoryArticle storyArticle = bundle.getParcelable(Constant.BOOK_INFO);
        if (storyArticle == null) return;
        currentChapter = bundle.getInt(Constant.CURRENT_CHAPTER);
        bookId = storyArticle.getId();
        mRetrofitService.getChapterList(storyArticle.getId(), chapterPage).enqueue(new BaseCallback<>(this, 1));
        tvTitle.setText(storyArticle.getArtName());
    }

    /**
     * 时刻监听系统亮度改变事件
     */
    private ContentObserver Brightness = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //LogUtils.d("BrightnessOnChange:" + ScreenUtils.getScreenBrightnessInt255());
            if (!ScreenUtils.isAutoBrightness(ReadActivity1.this)) {
                seekBarLightness.setProgress(ScreenUtils.getScreenBrightness());
            }
        }
    };

    private void initAASet() {
        curTheme = SettingManager.getInstance().getReadTheme();
        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);

        seekBarFontSize.setMax(10);
        //int fontSizePx = SettingManager.getInstance().getReadFontSize(bookId);
        int fontSizePx = SettingManager.getInstance().getReadFontSize();
        int progress = (int) ((ScreenUtils.pxToDpInt(fontSizePx) - 12) / 1.7f);
        seekBarFontSize.setProgress(progress);
        seekBarFontSize.setOnSeekBarChangeListener(new SeekBarChangeListener());

        seekBarLightness.setMax(100);
        seekBarLightness.setOnSeekBarChangeListener(new SeekBarChangeListener());
        seekBarLightness.setProgress(ScreenUtils.getScreenBrightness());
        isAutoLightness = ScreenUtils.isAutoBrightness(this);
        this.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS), true, Brightness);
        if (SettingManager.getInstance().isAutoBrightness()) {
            startAutoLightness();
        } else {
            stopAutoLightness();
        }

        gvAdapter = new ReadThemeAdapter(this, (themes = ThemeManager.getReaderThemeData(curTheme)), curTheme);
        gvTheme.setAdapter(gvAdapter);
        gvTheme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < themes.size() - 1) {
                    changedMode(false, position);
                } else {
                    changedMode(true, position);
                }
            }
        });
    }

    private void changedMode(boolean isNight, int position) {
        SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, isNight);
        AppCompatDelegate.setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_YES
                : AppCompatDelegate.MODE_NIGHT_NO);

        if (position >= 0) {
            curTheme = position;
        } else {
            curTheme = SettingManager.getInstance().getReadTheme();
        }
        gvAdapter.select(curTheme);
        mPageWidget.setTheme(isNight ? ThemeManager.NIGHT : curTheme);
        mPageWidget.setTextColor(ContextCompat.getColor(this, isNight ? R.color.chapter_content_night : R.color.chapter_content_day),
                ContextCompat.getColor(this, isNight ? R.color.chapter_title_night : R.color.chapter_title_day));
        mTvBookReadMode.setText(getString(isNight ? R.string.book_read_mode_day_manual_setting
                : R.string.book_read_mode_night_manual_setting));
        Drawable drawable = ContextCompat.getDrawable(this, isNight ? R.mipmap.ic_menu_mode_day_manual
                : R.mipmap.ic_menu_mode_night_manual);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mTvBookReadMode.setCompoundDrawables(null, drawable, null, null);
        ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
    }

    //    @OnClick({R.id.tvBookReadToc, R.id.tvBookReadMode})
    public void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.rl_progress:
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.CURRENT_CHAPTER, currentChapter);
                bundle.putString(Constant.BOOK_ID, bookId);
                bundle.putParcelableArrayList(Constant.BOOK_CHAPTER, chapList);
                toActivityForResult(CatalogActivity.class, bundle, REQUEST_CATALOG);
                break;
            case R.id.tv_progress:
//                gone(rlReadAaSet, rlReadMark);
                boolean isNight = !SharedPreferencesUtil.getInstance().getBoolean(Constant.ISNIGHT, false);
                changedMode(isNight, -1);
                break;
        }
    }

    @Override
    public void onSuccess(int requestCode, Object object) {
        super.onSuccess(requestCode, object);
        if (requestCode == 1) {
            BookCatalog bookCatalog = (BookCatalog) object;
            chapList = bookCatalog.getChapList();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }

    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekBarFontSize.getId() && fromUser) {
                calcFontSize(progress);
            } else if (seekBar.getId() == seekBarLightness.getId() && fromUser
                    && !SettingManager.getInstance().isAutoBrightness()) { // 非自动调节模式下 才可调整屏幕亮度
                ScreenUtils.saveScreenBrightnessInt100(progress, ReadActivity1.this);
                //SettingManager.getInstance().saveReadBrightness(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    private void startAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(true);
        ScreenUtils.startAutoBrightness(ReadActivity1.this);
        seekBarLightness.setEnabled(false);
    }

    private void stopAutoLightness() {
        SettingManager.getInstance().saveAutoBrightness(false);
        ScreenUtils.stopAutoBrightness(ReadActivity1.this);
        seekBarLightness.setProgress((int) (ScreenUtils.getScreenBrightnessInt255() / 255.0F * 100));
        seekBarLightness.setEnabled(true);
    }

    private void calcFontSize(int progress) {
        // progress range 1 - 10
        if (progress >= 0 && progress <= 10) {
            seekBarFontSize.setProgress(progress);
            mPageWidget.setFontSize(ScreenUtils.dpToPxInt(12 + 1.7f * progress));
        }
    }
}
